/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent, Fragment } from "react";
import { connect } from "dva";
import { Button, Form, Row, Col, Card, DatePicker, Select, Spin } from "antd";
import { debounce } from "lodash";
import moment from "moment";
import StandardTable from "@/components/StandardTable";
import AsyncDownLoad from "@/components/DownloadBar/AsyncDownLoad";
import styles from "./style.less";

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const dataFormat = "YYYY-MM-DD";

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 19 },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 5,
    },
  },
};

const columnsCash = [
  {
    title: "时间",
    dataIndex: "create_time",
  },
  {
    title: "资金流向",
    dataIndex: "trans_type",
    render: text => {
      return <span>{text == "out" ? "流出" : "流入"}</span>;
    },
  },
  {
    title: "资金类型",
    dataIndex: "type",
    render: (text, { cm_id = [] }) => {
      const cm_ids =
        cm_id.length > 1 ? `（${cm_id[0]}等）` : cm_id.length == 1 ? `（${cm_id[0]}）` : "";
      return (
        <span>
          {text} <span style={{ color: "red" }}>{cm_ids}</span>
        </span>
      );
    },
  },
  {
    title: "金额",
    dataIndex: "money",
    render: (text, record) => {
      return <span>{record.trans_type == "out" ? `-${text}` : `+${text}`}</span>;
    },
  },
  {
    title: "订单编号",
    dataIndex: "order_number",
    render: text => {
      return <a>{text}</a>;
    },
  },
];
@connect(({ loading, account }) => ({
  account,
  detailLoading: loading.effects["account/getAccountDetail"],
  selectLoading: loading.effects["account/getTypeOptions"],
}))
@Form.create()
export default class Account extends PureComponent {
  handleSearch = debounce(
    e => {
      e.preventDefault();
      this.getAccountDetail();
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  componentDidMount() {
    this.getAccountDetail();
  }

  componentWillUnmount() {
    this.timer && clearInterval(this.timer);
  }

  handleStandardTableChange = e => {
    this.getAccountDetail(e.current, "", e.pageSize);
  };

  getAccountDetail = (page = 1, d_l = "", size = 20) => {
    const {
      form: { getFieldValue, getFieldsValue },
      dispatch,
      type,
    } = this.props;
    const values = getFieldsValue(["businessType", "type"]);

    const date = getFieldValue("date");
    if (!d_l) {
      dispatch({
        type: "account/getAccountDetail",
        payload: {
          page,
          pageSize: size,
          startTime: moment(date[0]).format(dataFormat),
          endTime: moment(date[1]).format(dataFormat),
          accountType: type,
          ...values,
        },
      });
    } else {
      return {
        startTime: moment(date[0]).format(dataFormat),
        endTime: moment(date[1]).format(dataFormat),
        accountType: type,
        ...values,
      };
    }
  };

  downloadData = () => {
    const { type } = this.props;
    const query = {
      data: JSON.stringify({
        data: {
          accountType: type,
          ...this.getAccountDetail("", 1),
          d_l: 1,
        },
        run: "/FundsAccount/capitalFlow2",
        time: new Date().getTime(),
      }),
    };
    return {
      ...query,
    };
  };

  myFilter = (param, str) => param.filter(item => item.title !== str);

  onDropdownVisibleChange = () => {
    const { dispatch, type } = this.props;
    dispatch({
      type: "account/getTypeOptions",
      payload: {
        accountType: type,
      },
    });
  };

  render() {
    const { form, account, detailLoading, selectLoading, type: accountType } = this.props;
    const { getFieldDecorator, getFieldsValue } = form;
    const { type } = getFieldsValue();
    const { typeSelectValue } = account;
    const tableList = account[`${accountType}DetailList`] || {};
    const exportDisabled = !tableList.list || (tableList.list && tableList.list.length === 0);

    return (
      <Fragment>
        <Card bordered={false} bodyStyle={{ padding: "24px 0 24px" }}>
          <Form onSubmit={this.handleSearch} className={styles["search-form"]}>
            <Row type="flex">
              <Col xs={24} md={12}>
                <FormItem {...formItemLayout} label="流水日期">
                  {getFieldDecorator("date", {
                    initialValue: [moment(new Date()).add(-1, "month"), moment(new Date())],
                  })(
                    <RangePicker style={{ width: "100%" }} placeholder={["开始日期", "结束日期"]} />
                  )}
                </FormItem>
              </Col>
              <Col xs={24} md={12}>
                <FormItem {...formItemLayout} label="资金类型">
                  {getFieldDecorator("businessType", {
                    initialValue: "",
                  })(
                    <Select
                      placeholder="请选择资金类型"
                      onDropdownVisibleChange={this.onDropdownVisibleChange}
                    >
                      {selectLoading ? (
                        <Option disabled value="loading">
                          <Spin />
                        </Option>
                      ) : (
                        <Option key="all" value="">
                          所有类型
                        </Option>
                      )}
                      {typeSelectValue &&
                        Object.keys(typeSelectValue).map(item => (
                          <Option key={item} value={item}>
                            {typeSelectValue[item]}
                          </Option>
                        ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex">
              <Col xs={24} md={12}>
                <FormItem label="资金流向" {...formItemLayout}>
                  {getFieldDecorator("type", {
                    initialValue: "",
                  })(
                    <Select placeholder="请选择资金流向" allowClear>
                      <Option value="">所有资金流向</Option>
                      <Option value="in">资金流入</Option>
                      <Option value="out">资金流出</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col xs={24} md={12}>
                <FormItem {...tailFormItemLayout}>
                  <Row type="flex" gutter={[40, 0]}>
                    <Col>
                      <Button
                        type="primary"
                        icon="search"
                        htmlType="submit"
                        key="search"
                        loading={detailLoading}
                      >
                        查询
                      </Button>
                    </Col>
                    <Col>
                      <AsyncDownLoad
                        disabled={exportDisabled}
                        action="/Api/Handle/run"
                        data={this.downloadData}
                      >
                        <Button type="primary" icon="download">
                          导出
                        </Button>
                      </AsyncDownLoad>
                    </Col>
                  </Row>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Card>
        <StandardTable
          rowKey={({ trans_type, id }) => `${trans_type}-${id}`}
          loading={detailLoading}
          data={tableList}
          columns={type == "in" ? this.myFilter(columnsCash, "订单编号") : columnsCash}
          onChange={this.handleStandardTableChange}
        />
      </Fragment>
    );
  }
}
